// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// D [author] rhyme_lph
// p [email]  rhymelph@gmail.com
// E [github] https://github.com/rhymelph

import 'dart:async';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/account_entity.dart';
import 'package:finance_app/src/entities/business_contact_entity.dart';
import 'package:finance_app/src/entities/custom_expense_data.dart';
import 'package:finance_app/src/entities/employee_contact_entity.dart';
import 'package:finance_app/src/entities/expense_detail_entity.dart';
import 'package:finance_app/src/entities/fixed_asset_entity.dart';
import 'package:finance_app/src/entities/format/split_expense_entity.dart';
import 'package:finance_app/src/entities/ocr_attachment_entity.dart';
import 'package:finance_app/src/entities/setting_data_entity.dart';
import 'package:finance_app/src/http_service/http_asset_service.dart';
import 'package:finance_app/src/http_service/http_expense_service.dart';
import 'package:finance_app/src/mixin/check_plan_mixin.dart';
import 'package:finance_app/src/mixin/form_category_gst_mixin.dart';
import 'package:finance_app/src/mixin/from_attach_mixin.dart';
import 'package:finance_app/src/mixin/init_edit_data_mixin.dart';
import 'package:finance_app/src/provider/dashboard/purchase/purchases_provider.dart';
import 'package:finance_app/src/provider/dashboard/purchase/views/purchases_expense_provider.dart';
import 'package:finance_app/src/provider/dashboard/purchase/views/purchases_summary_provider.dart';
import 'package:finance_app/src/provider/hr_payroll/hr_and_payroll_provider.dart';
import 'package:finance_app/src/provider/hr_payroll/views/employee_provider.dart';
import 'package:finance_app/src/provider/hr_payroll/views/reimburse_provider.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/widgets/bottom_sheet/calendar_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/currency_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/delete_info_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_info_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_tip_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/judge_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/list_select_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/text_area_input_bottom_sheet.dart';
import 'package:flutter/material.dart';

class NewExpenseProvider extends BaseProvider<ExpenseDetailEntity>
    with
        FormAttachMixin,
        FormCategoryGstMixin,
        InitEditDataMixin<ExpenseDetailEntity>,
        CheckPlanMixin {
  BusinessContactEntity paidTo;

  DateTime date;

  SettingDataPaymentType paymentMethod;

  SettingDataPaidUsing paidUsing;

  SettingDataCurrency unit;

  AccountEntity bankAccount;

  EmployeeContactEntity paidBy;

  List<String> menuList = [];

  TextEditingController priceController = TextEditingController();
  FocusNode priceFocusNode = FocusNode();

  TextEditingController notesController = TextEditingController();
  FocusNode notesFocusNode = FocusNode();

  TextEditingController expenseNumberController = TextEditingController();
  FocusNode expenseFocusNode = FocusNode();

  bool isSelectMode = false;

  bool isPaid = true;

  bool isClosed = false;

  DateTime dueDate;

  String businessName;

  num unpaid;

  bool get isEqualPrice => CashUtils.checkEqual(priceController.text, total);

  @override
  void dispose() {
    super.dispose();
    priceController.dispose();
    priceFocusNode.dispose();
    notesController.dispose();
    notesFocusNode.dispose();
    expenseNumberController.dispose();
    expenseFocusNode.dispose();
  }

  void unFocus() {
    notesFocusNode.unfocus();
    priceFocusNode.unfocus();
    expenseFocusNode.unfocus();
  }

  @override
  Future get editDataFuture =>
      id == null ? null : HttpExpenseService.showExpense(id);

  @override
  void initState() {
    super.initState();
    priceController.addListener(() {
      update();
    });
  }

  void onSave() async {
    unFocus();
    if (!isEqualPrice) {
      print('total:$total , price:${priceController.text}');
      return;
    }
    if (priceController.text.length == 0) {
      showToast(S.current.please_enter_the_price);
      return;
    }

    if (paidTo == null) {
      showToast(S.current.please_select_paid_to);
      return;
    }

    if (expenseNumberController.text.length == 0) {
      showToast(S.current.please_enter_expense_number);
      return;
    }

    if (date == null) {
      showToast(S.current.please_select_date);
      return;
    }

    if (isPaid == true) {
      if (paymentMethod == null) {
        showToast(S.current.please_select_payment_method);
        return;
      }
      if (paidUsing == null) {
        showToast(S.current.please_select_paid_using);
        return;
      }
      if (paidUsing.key == 'company' && bankAccount == null) {
        showToast(S.current.please_select_bank_account);
        return;
      }
      if (paidUsing.key == 'personal' && paidBy == null) {
        showToast(S.current.please_select_bank_paid_by);
        return;
      }
    } else {
      if (dueDate == null) {
        showToast(S.current.please_select_due_date);
        return;
      }
    }

    for (final item in splitList) {
      if (item.selectTax == null) {
        showToast(S.current.please_select_tax);
        return;
      }
    }
    if (!isEdit) {
      for (final item in splitList) {
        if (item.selectCategory.key == 'plant_fixed_assets' ||
            item.selectCategory.key == 'equipment_fixed_assets' ||
            item.selectCategory.key == 'renovation_fixed_assets' ||
            item.selectCategory.key == 'vehicle_fixed_assets' ||
            item.selectCategory.key == 'other_fixed_assets') {
          if (item.fixedAssetEntity == null) {
            onAddFixedAssetData(item);
            return;
          }
        }
      }
    }
    List<int> attachmentIds = await uploadFiles();
    if (attachmentIds == null) return;

    double _total = double.parse(priceController.text, (e) => null);

    String notes = notesController.text;
    List items = splitList
        .map((e) => {
              'category_id': e.selectCategory.id,
              'price': e.amount,
              'is_tax_inclusive': e.isCheckInclusive == true ? 1 : 0,
              'tax_id': e.selectTax.id,
              'tax_amount':
                  double.parse(e.amount, (e) => 0.00) * e.selectTax.rate / 100
            })
        .toList();
    ExpenseDetailEntity orderEntity;

    if (isEdit == true) {
      await post(
          HttpExpenseService.updateExpense(
              id: data?.id,
              contactId: paidTo?.id,
              number: expenseNumberController.text,
              issuedAt: DateTimeUtils.formatDateTime(date, 'yyyy-MM-dd'),
              currencyCode: unit?.key,
              subtotal: subTotal,
              inclusiveTaxAmount: includesGST,
              exclusiveTaxAmount: gst,
              total: _total,
              paidUsing: paidUsing?.key,
              paidByEmployeeId: paidBy?.id,
              accountId: bankAccount?.id,
              paymentTypeId: paymentMethod?.id,
              attachmentIds: attachmentIds,
              items: items,
              notes: notes,
              dueDate: DateTimeUtils.formatDateTime(dueDate, 'yyyy-MM-dd')),
          autoHandler: AutoHandler.Toast, onSuccess: (result) {
        orderEntity = getEntityFromResult<ExpenseDetailEntity>(result);
      });
    } else {
      await post(
          HttpExpenseService.createExpense(
              contactId: paidTo?.id,
              number: expenseNumberController.text,
              issuedAt: DateTimeUtils.formatDateTime(date, 'yyyy-MM-dd'),
              currencyCode: unit?.key,
              subtotal: subTotal,
              inclusiveTaxAmount: includesGST,
              exclusiveTaxAmount: gst,
              total: _total,
              paidUsing: isPaid ? paidUsing?.key : null,
              paidByEmployeeId: isPaid ? paidBy?.id : null,
              accountId: isPaid ? bankAccount?.id : null,
              paymentTypeId: isPaid ? paymentMethod?.id : null,
              attachmentIds: attachmentIds,
              items: items,
              notes: notes,
              dueDate: !isPaid
                  ? DateTimeUtils.formatDateTime(dueDate, 'yyyy-MM-dd')
                  : null),
          autoHandler: AutoHandler.Toast, onSuccess: (result) async {
        orderEntity = getEntityFromResult<ExpenseDetailEntity>(result);
        await onCreateFixedAsset(orderEntity.id);
      });
    }

    if (orderEntity != null) {
      updateDashboard();

      if (isSelectMode == true) {
        obtainContext?.call((context) {
          Navigator.of(context).pop(orderEntity);
        });
      } else {
        id = orderEntity?.id;
        await post(editDataFuture,
            loadingTip: S.current.loading,
            autoHandler: AutoHandler.Toast, onSuccess: (result) {
          isEdit = false;
          data = transformData(
              getEntityFromResult<ExpenseDetailEntity>(result), false);
          update();
        });
      }
    }
  }

  void onChangeUnit() {
    unFocus();
    obtainContext?.call((context) async {
      unit = await showCurrencyBottomSheet(context, unit);
      update();
    });
  }

  void onSelectPaymentMethod() {
    unFocus();
    obtainContext?.call((context) async {
      paymentMethod =
          await showPaymentMethodBottomSheet(context, paymentMethod);
      update();
    });
  }

  void onChangePaidTo() async {
    unFocus();
    final result = await Routes.navigateTo(
        RouterGenProviders.businessContactsPage,
        params: {
          'select': paidTo,
        });
    if (result != null) {
      paidTo = result;
      update();
    }
  }

  void onChangeDate() {
    unFocus();
    obtainContext?.call((context) async {
      date = await showCalendarBottomSheet(context, date);
      update();
    });
  }

  void onChangePaidUsing() {
    unFocus();
    obtainContext?.call((context) async {
      paidUsing = await showPaidUsingBottomSheet(context, paidUsing);
      if (paidUsing?.key == 'personal' && paidBy == null) {
        paidBy = await Config.getEmployeeMe(this);
      }
      update();
    });
  }

  void onChangeBankAccount() {
    unFocus();
    obtainContext?.call((context) async {
      final data =
          await Routes.navigateTo(RouterGenProviders.bankAccountPage, params: {
        'select': bankAccount,
      });
      if (data != null) {
        bankAccount = data;
        update();
      }
    });
  }

  void onChangePaidBy() {
    unFocus();
    obtainContext?.call((context) async {
      final data = await Routes.navigateTo(
          RouterGenProviders.employeeContactsPage,
          params: {
            'select': paidBy,
          });
      if (data != null) {
        paidBy = data;
        update();
      }
    });
  }

  void onSelectMenu(String value) {
    if (value == S.current.reimburse_now) {
      onReimburseNow();
    } else if (value == S.current.reimburse_later) {
      onReimburseLater();
    } else if (value == S.current.reject) {
      onReject();
    } else if (value == S.current.delete) {
      onDelete();
    } else if (value == S.current.edit) {
      onChangeEditMode();
    } else if (value == S.current.make_payment) {
      onAddPayment();
    } else if (value == S.current.see_payment) {
      onSeePayment();
    } else if (value == S.current.withdraw) {
      onWithdraw();
    }
  }

  @override
  FutureOr<ExpenseDetailEntity> transformData(
      ExpenseDetailEntity d, bool isCache) {
    splitList.clear();
    date = DateTimeUtils.toDateTime(d.issuedAt);
    paymentMethod = d.paymentType;
    paidUsing = Config.settingData?.paidUsing?.firstWhere(
        (element) => element.key == d.paidUsing,
        orElse: () => null);
    expenseNumberController.text = d.number;
    unit = Config.settingData?.currency?.firstWhere(
        (element) => element.key == d.currencyCode,
        orElse: () => null);
    bankAccount = d.account;
    paidTo = d.contact;
    paidBy = EmployeeContactEntity()
      ..id = d.paidByEmployeeId
      ..name = d.paidBy;
    // paidBy = d.pay
    // SettingDataCurrency unit;
    // AccountEntity bankAccount;
    // EmployeeContactEntity paidBy;
    priceController.text = d.total?.toStringAsNotFixed(2);
    notesController.text = d.notes;
    for (final data in d.items) {
      splitList.add(data.toExpense());
    }
    isPaid = d.dueAt == null || d.paymentTypeId != null;
    // || d.paymentTypeId != null || !(d.status =='open'&& d.paidUsing=='company')
    dueDate = DateTimeUtils.toDateTime(d.dueAt, 'yyyy-MM-dd HH:mm:ss');
    unpaid = d.unpaid ?? d.total;
    //是否为自己
    bool canManager = Config.hasPermission(PermissionUtils.hrPayroll);
    bool isCompany = paidUsing?.key?.startsWith('company') ?? false;
    bool isOpen = d.status == 'open';
    bool isLater = d.reimburseStatus == 'later';
    bool isReimbursePending = d.reimburseStatus == 'pending';
    bool isReject = d.status == 'rejected';
    bool isAddedToPayslip = d.reimburseStatus == 'later';
    bool isPayslipPaid = d.isPayslipPaid == 1;

    isClosed = d.status == 'closed';
    menuList.clear();
    if (isPaid) {
      if (isCompany) {
        //公司报销
        if (canManager) {
          if (isOpen) {
            menuList = [S.current.see_payment, S.current.make_payment];
          }
        } else {
          menuList = [];
          if (isOpen) {
            menuList = [
              S.current.edit,
              S.current.delete,
            ];
          }
        }
        if (!isOpen && !isLater && !isReject) {
          menuList.add(S.current.see_payment);
        }
      } else {
        if (isPaid && !isLater && !isReject) {
          menuList.add(S.current.see_payment);
        }
        //个人报销
        if (canManager && isReimbursePending) {
          menuList = [
            S.current.edit,
            S.current.delete,
            S.current.reimburse_now,
            S.current.reimburse_later,
            S.current.reject,
          ];
        } else {
          if (isOpen) {
            menuList = [
              S.current.edit,
              S.current.delete,
            ];
          }
        }
      }
    } else {
      if (canManager && isOpen && !isPaid) {
        menuList = [S.current.edit, S.current.delete, S.current.make_payment];
      } else if (canManager && !isOpen && !isPaid) {
        menuList = [S.current.edit];
        if (!isLater && !isReject) {
          menuList.add(S.current.see_payment);
        }
      } else if (!isLater && !isReject) {
        menuList = [S.current.see_payment];
      }
    }

    if (isAddedToPayslip && !isPayslipPaid) {
      menuList = [S.current.withdraw];
    }

    if (!Config.hasPermission(PermissionUtils.cashBank)) {
      menuList.remove(S.current.see_payment);
      menuList.remove(S.current.make_payment);
    }

    handleDataUpdate(d);
    return super.transformData(d, isCache);
  }

  void onReimburseNow() async {
    if (isPlanExpired()) return;
    CustomExpenseData customData = CustomExpenseData(
        ids: [id],
        orderType: 'reimburse',
        paidTo: paidBy.name,
        number: data.number,
        date: date.toIso8601String(),
        totalAmount: total);
    final result =
        await Routes.navigateTo(RouterGenProviders.newCashOutPage, params: {
      'customExpenseData': customData,
      'expenseNumber': numberCtl.text,
      'currency': unit
    });

    if (result != null) {
      updateDashboard();
      data = transformData(result, false);
      update();
    }
  }

  void updateDashboard() {
    // issue
    Providers.get<HrAndPayrollProvider>(
            RouterGenProviders.hrAndPayrollPage, null)
        ?.getChildProvider<ReimburseProvider>()
        ?.refreshController
        ?.requestRefresh();
    if (!Config.hasPermission(PermissionUtils.homeDashboard)) {
      final homeProvider = Config.dashboardProvider;

      homeProvider
          ?.getChildProvider<HrAndPayrollProvider>()
          ?.getChildProvider<EmployeeProvider>()
          ?.refreshController
          ?.requestRefresh();

      homeProvider
          ?.getChildProvider<HrAndPayrollProvider>()
          ?.getChildProvider<ReimburseProvider>()
          ?.refreshController
          ?.requestRefresh();
    }

    Providers.get<PurchasesProvider>(RouterGenProviders.purchasesPage, null)
        ?.getChildProvider<PurchasesSummaryProvider>()
        ?.loadData();
    Providers.get<PurchasesProvider>(RouterGenProviders.purchasesPage, null)
        ?.getChildProvider<PurchasesExpenseProvider>()
        ?.loadData();
  }

  void onReimburseLater() {
    if (isPlanExpired()) return;
    obtainContext?.call((context) async {
      final result = await showReimburseLaterJudgeBottomSheet(
        context,
      );
      if (result == true) {
        ExpenseDetailEntity entity;
        await post(HttpExpenseService.reimburseLaterExpense(id),
            loadingTip: S.current.loading,
            autoHandler: AutoHandler.Toast, onSuccess: (result) {
          entity = getEntityFromResult<ExpenseDetailEntity>(result);
        });
        if (entity != null) {
          updateDashboard();

          data = await transformData(entity, false);
          update();
          showReimbursementTipBottomSheet(context, onGotIt: () {
            Navigator.of(context).pop();
          });
        }
      }
    });
  }

  void onReject() {
    if (isPlanExpired()) return;
    obtainContext?.call((context) async {
      final result =
          await showRejectExpenseInputBottomSheet(context, onReject: (data) {
        Navigator.of(context).pop(data);
      });
      if (result != null) {
        ExpenseDetailEntity entity;
        await post(HttpExpenseService.reimburseReject(data.id, reason: result),
            loadingTip: S.current.loading,
            autoHandler: AutoHandler.Toast, onSuccess: (result) {
          entity = getEntityFromResult<ExpenseDetailEntity>(result);
        });
        if (entity != null) {
          updateDashboard();

          await showRejectedTipBottomSheet(context);
          data = transformData(entity, false);
          update();
        }
      }
    });
  }

  void onDelete() {
    if (isPlanExpired()) return;
    obtainContext?.call((context) async {
      bool isSuccess =
          await showDeleteExpenseInfoBottomSheet(context, onCancel: () {
        Navigator.of(context).pop(false);
      }, onDelete: () {
        Navigator.of(context).pop(true);
      });
      if (isSuccess == true) {
        isSuccess = false;
        await post(HttpExpenseService.deleteExpense(data.id),
            loadingTip: S.current.loading,
            autoHandler: AutoHandler.Toast, onSuccess: (result) {
          isSuccess = true;
        });
        if (isSuccess == true) {
          updateDashboard();
          await showExpenseDeleteSuccessTipBottomSheet(context);
          Navigator.of(context).pop({
            'delete': true,
          });
          Config.dashboardProvider
              .onRefreshDashboard(refreshTransaction: false);
        }
      }
    });
  }

  void onWithdraw() {
    if (isPlanExpired()) return;
    obtainContext?.call((context) async {
      bool isSuccess =
          await showWithdrawExpenseInfoBottomSheet(context, onCancel: () {
        Navigator.of(context).pop(false);
      }, onDelete: () {
        Navigator.of(context).pop(true);
      });
      if (isSuccess == true) {
        isSuccess = false;
        await post(HttpExpenseService.withdrawReimburse(data.id),
            loadingTip: S.current.loading,
            autoHandler: AutoHandler.Toast, onSuccess: (result) {
          isSuccess = true;
        });
        if (isSuccess == true) {
          updateDashboard();
          await showExpenseWithdrawSuccessTipBottomSheet(context);
          Navigator.of(context).pop({
            'delete': true,
          });
        }
      }
    });
  }

  void initExpense(ExpenseDetailEntity expenseData) {
    if (expenseData == null) return;
    isEdit = false;
    id = expenseData.id;
  }

  void initOcrData(OcrAttachmentOcrData ocrData) {
    if (ocrData == null) return;
    splitList.clear();
    date = DateTimeUtils.toDateTime(ocrData.orderDate);
    paymentMethod = ocrData.paymentType;
    date = DateTimeUtils.toDateTime(ocrData.orderDate, 'yyyy-MM-dd');
    // paidUsing = Config.settingData.paidUsing
    //     .firstWhere((element) => element.key == d.paidUsing);
    unit = Config.settingData.currency
        .firstWhere((element) => element.key == ocrData.currency);
    // bankAccount = d.account;
    paidTo = ocrData.contact;
    // SettingDataCurrency unit;
    // AccountEntity bankAccount;
    // EmployeeContactEntity paidBy;
    businessName = ocrData.businessContactName;
    for (final data in ocrData.items) {
      if (data.tax == null) {
        data.tax = Config.settingInfo.taxData;
      }
      splitList.add(data.toExpense());
    }
    priceController.text = ocrData.total?.toStringAsNotFixed(2);
  }

  @override
  List<OcrAttachmentEntity> get attachments => data?.attachments;

  @override
  String get type => 'expense';

  @override
  TextEditingController get numberCtl => expenseNumberController;

  void onChangePaidStatus(bool value) {
    if (isPaid != value) {
      isPaid = value;
      if (isPaid == false) {
        dueDate = null;
      } else {
        paymentMethod = null;
        paidUsing = null;
        bankAccount = null;
        paidBy = null;
      }
      update();
    }
  }

  void onChangeDueDate() {
    unFocus();
    obtainContext?.call((context) async {
      dueDate = await showCalendarBottomSheet(context, dueDate,
          startDate: date, withinFinancialYear: false);
      update();
    });
  }

  void onAddPayment() async {
    if (isPlanExpired()) return;
    final result =
        await Routes.navigateTo(RouterGenProviders.newCashOutPage, params: {
      'isSelectMode': true,
      'expenseId': data.id,
      'paidTo': paidTo,
      'currency': unit,
      'total': unpaid,
      'expenseNumber': numberCtl.text
    });
    if (result != null) {
      onTry();
      updateDashboard();
    }
  }

  void onSeePayment() async {
    await Routes.navigateTo(RouterGenProviders.seePaymentPage,
        params: {'expenseId': id, 'isClosed': isClosed});
    loadData();
    updateDashboard();
  }

  void onSettingPaidBy() async {
    if (paidUsing?.key == 'personal' && paidBy == null) {
      await Future.delayed(Duration(milliseconds: 600));
      paidBy = await Config.getEmployeeMe(this);
      update();
    }
  }

  Future<void> onSplitExpense({String type}) async {
    unFocus();
    if (!isEdit) {
      for (final item in splitList) {
        if (item.selectCategory.key == 'plant_fixed_assets' ||
            item.selectCategory.key == 'equipment_fixed_assets' ||
            item.selectCategory.key == 'renovation_fixed_assets' ||
            item.selectCategory.key == 'vehicle_fixed_assets' ||
            item.selectCategory.key == 'other_fixed_assets') {
          if (item.fixedAssetEntity == null) {
            onAddFixedAssetData(item);
            return;
          }
        }
      }
    }

    final result =
        await Routes.navigateTo(RouterGenProviders.selectCategoryPage, params: {
      'type': type,
      'unit': unit,
    });
    if (result != null) {
      SettingDataCategory selectCategory = result['category'];
      SettingDataTax selectTax = result['gst'];
      String amount = result['amount'];
      bool isCheckInclusive = result['isCheckInclusive'];
      SplitExpenseEntity splitExpense = SplitExpenseEntity()
        ..selectCategory = selectCategory
        ..selectTax = selectTax
        ..amount = amount
        ..isCheckInclusive = isCheckInclusive;
      splitList.add(splitExpense);
      update();
      if (selectCategory.key == 'plant_fixed_assets' ||
          selectCategory.key == 'equipment_fixed_assets' ||
          selectCategory.key == 'renovation_fixed_assets' ||
          selectCategory.key == 'vehicle_fixed_assets' ||
          selectCategory.key == 'other_fixed_assets') {
        onAddFixedAssetData(splitExpense);
      }
    }
  }

  void onAddFixedAssetData(SplitExpenseEntity expenseEntity) {
    obtainContext?.call((context) async {
      await showRecordFixedAssetAdditionInfoBottomSheet(context,
          onGotIt: () async {
        num total = num.tryParse(expenseEntity.amount);
        num amountWithoutTax = expenseEntity.isCheckInclusive
            ? total -
                calInclusiveGST(total, expenseEntity.selectTax.rate / 100 ?? 0)
            : total;
        Navigator.pop(context);
        final FixedAssetEntity result = await Routes.navigateTo(
            RouterGenProviders.newFixedAssetPage,
            params: {
              'fixedAsset': FixedAssetEntity()
                ..price = amountWithoutTax.toStringAsFixed(2)
                ..number = paidTo?.name
                ..purchasedAt = date.toIso8601String()
                ..currencyCode = unit?.key
                ..category = expenseEntity.selectCategory.name
                ..lifespan = 36
                ..bookValueAfter = 0
                ..depreciationType = 'straight'
            });

        if (result != null) {
          expenseEntity.fixedAssetEntity = result;
        }
      });
      update();
    });
  }

  Future<void> onCreateFixedAsset(int expenseID) async {
    List<SplitExpenseEntity> fixedAssets =
        splitList.where((element) => element.fixedAssetEntity != null).toList();
    await Future.forEach(fixedAssets, (SplitExpenseEntity e) async {
      await post(
          HttpAssetService.createAsset(
            name: e?.fixedAssetEntity?.name,
            category: e?.selectCategory?.key,
            type: "expense",
            type_id: expenseID,
            purchased_at: DateTimeUtils.formatDateTime(date, 'yyyy-MM-dd'),
            currency_code: unit?.key,
            price: num.parse(e.fixedAssetEntity.price, (e) => null),
            book_value_after: e.fixedAssetEntity?.bookValueAfter,
            depreciation_type: e.fixedAssetEntity.depreciationType,
            lifespan: e.fixedAssetEntity.lifespan,
          ),
          loadingTip: S.current.loading,
          autoHandler: AutoHandler.Toast);
    });
  }

  @override
  Future<void> onSelectItem(SplitExpenseEntity value, String type) async {
    await super.onSelectItem(value, type);
  }
}
